/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javamail.sip;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 *
 * @author sriram
 */
public class sipMessageSender extends Thread{
    String msg = null;
    String hostName = null;
    int port = 5060;
    
    private static final boolean debugEnabled = true;
    private static final boolean msgDebug = true;

    
    public sipMessageSender(String msg, String hostName, int port) {
        this.msg = msg;
        this.hostName = hostName;
        this.port = port;
    }

    public void run() {
        if(msg != null) {
            try {
                byte[] buf = msg.getBytes();
                if(msgDebug) {
                    System.out.println("sipMessageSender::run-Outgoing Message sent-");
                    System.out.println(msg);
                }
                InetAddress address = null;
                if(isValidIp(hostName)) {
                    address = InetAddress.getByAddress(hostName.getBytes());
                } else {
                    if(debugEnabled)
                        System.out.println("sipMessageSender::run-Invalid IP, sending using host name");
                    address = InetAddress.getByName(hostName);
                }
                // Create an object of type DatagramPacket and queue it in sipUASend class
                // for sending
                DatagramPacket pkt = new DatagramPacket(buf, buf.length, address, port);
                sipUASend.send(pkt);
            } catch (UnknownHostException e) {
                if(debugEnabled)
                    System.out.println("sipMessageSender::send-Unable to find hostname");
            } catch (Exception e) {
                if(debugEnabled)
                    System.out.println("sipMessageSender::send-Unknown exception:"+e.getMessage());
            }
        }
    }

    public boolean isValidIp(final String ip) {
        boolean correctFormat = ip.matches("^[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}$");
        boolean validIp = false;
        if (correctFormat) {
            validIp = true;
            String [] values = ip.split("\\.");
            if(values.length!=3)
                validIp = false;
            else {
                for (int k = 0; k < values.length; ++k) {
                    short v = Short.valueOf(values[k]).shortValue();
                    if ((v < 0) || (v > 255)) {
                        validIp = false;
                    }
                }
            }
        }
        return validIp;
    }

}
